﻿using MongoDB.Driver;
using Sustainalytics.ClientDW.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ScreeningTool.Synchronization.Handlers.ESG
{
    public class IncidentHandler : IHandlerWithGrouping<Incident>
    {
        public ProjectionDefinition<Incident> GetProjection(ProjectionDefinitionBuilder<Incident> builder) => builder
            .Include(x => x.HasSupplyChainSpecialTag)
            .Include(x => x.EventIndicatorName)
            .Include(x => x.MainTag)
            .Include(x => x.ImpactScore)
            .Include(x => x.RiskScore);

        public IEnumerable<ExtraElement> GetExtraElements(IEnumerable<Incident> entities) => entities
            .Select(incident => new
            {
                Key = incident.EventIndicatorName + " - " + incident.MainTag,
                IncidentScore = Math.Max(incident.ImpactScore, incident.RiskScore).ToInt(),
                ImpactScore = incident.ImpactScore.ToInt(),
                RiskScore = incident.RiskScore.ToInt(),
            })
            .GroupBy(x => x.Key)
            .Select(grp => grp.OrderByDescending(x => x.IncidentScore).First())
            .SelectMany(x => new ExtraElementList
            {
                { $"{x.Key}-Answer Category",        x.IncidentScore },
                { $"{x.Key}-Impact Answer Category", x.ImpactScore   },
                { $"{x.Key}-Risk Answer Category",   x.RiskScore     },
            });
    }
}
